<template>
  <div class="map-layout">
    <div class="map-container">
      <div class="map-info">
        <!-- 修改起点显示逻辑 -->
        <p v-if="navigating && currentPositionMarker">
          📍 当前位置: {{ getPositionString(currentPositionMarker.getPosition()) }}
        </p>
        <p v-else-if="marker1">
          📍 起点: {{ marker1.lng }}, {{ marker1.lat }}
        </p>

        <p v-if="marker2">📍 终点: {{ marker2.lng }}, {{ marker2.lat }}</p>
        <p v-if="distance > 0">📏 距离: {{ distance.toFixed(2) }} 米</p>

        <!-- 路线信息 -->
        <div v-if="routeInfo">
          <p>🚗 路线距离: {{ routeInfo.distance }} 米</p>
          <p>⏱️ 预计时间: {{ routeInfo.time }} 分钟</p>
        </div>
      </div>

      <!-- 添加清除按钮 -->
      <el-button
          v-if="marker1 || marker2"
          @click="clearMarkers"
          type="danger"
          size="small"
          class="clear-btn"
      >
        清除标记
      </el-button>


      <div id="container" class="amap"></div>
      <div v-if="loading" class="map-loading">地图加载中...</div>
    </div>


  </div>


  <div class="navigation-controls">
    <el-button
        v-if="!navigating && marker2"
        @click="startNavigation"
        type="success"
        size="small"
    >
      开始导航
    </el-button>

    <el-button
        v-if="navigating"
        @click="stopNavigation"
        type="danger"
        size="small"
    >
      停止导航
    </el-button>
  </div>

  <!-- 在路线信息区域添加导航指示 -->
  <div v-if="routeInfo && navigating" class="nav-instructions">
    <p>🛣️ 当前路线: {{ routeInfo.instruction }}</p>
    <p>⬆️ 下一路段: {{ routeInfo.nextInstruction }}</p>
  </div>














</template>

<script setup>
import {ref, onMounted,nextTick,onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'


// 新增实时定位相关变量
const watchId = ref(null)
const currentPositionMarker = ref(null)
const loading = ref(true)
let map = null
const marker1 = ref(null)
const marker2 = ref(null)
const distance = ref(0)
const driving = ref(null) // 路线规划实例
const routeInfo = ref(null) // 路线信息
// 新增导航状态变量
const navigating = ref(false)
let navInterval = null
const showAddDialog = ref(false)
const newStation = ref({
  name: '',
  address: '',
  positionStr: '',
  position: null
})
const stationMarkers = ref([]) // 存储快递站标记


onMounted(() => {
  nextTick(() => {
    initMap();
    startRealtimeLocation() // 新增实时定位启动
  });
});

// 新增：实时定位函数
function startRealtimeLocation() {
  if (navigator.geolocation) {
    watchId.value = navigator.geolocation.watchPosition(
        position => {
          const lat = position.coords.latitude
          const lng = position.coords.longitude

          // 移除旧的定位标记
          if (currentPositionMarker.value) {
            map.remove(currentPositionMarker.value)
          }

          // 创建新的定位标记
          currentPositionMarker.value = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),
            content: '<div class="current-position-marker">📍</div>'
          })
          map.add(currentPositionMarker.value)
          map.setCenter([lng, lat])
        },
        error => {
          console.error('实时定位失败:', error)
          ElMessage.error('实时定位失败: ' + error.message)
        },
        {
          enableHighAccuracy: true, // 高精度模式
          timeout: 5000,            // 超时时间
          maximumAge: 0             // 不使用缓存位置
        }
    )
  } else {
    ElMessage.warning('浏览器不支持地理定位功能')
  }
}

// 新增：组件卸载时清除定位监听
onUnmounted(() => {
  if (watchId.value !== null) {
    navigator.geolocation.clearWatch(watchId.value)
  }
})
// 新增位置格式化函数
function getPositionString(pos) {
  return `${pos.lng.toFixed(6)}, ${pos.lat.toFixed(6)}`
}


// 停止导航函数
function stopNavigation() {
  navigating.value = false
  clearInterval(navInterval)
  if (driving.value) {
    driving.value.clear()
  }
  // 确保调用保存函数
  saveHistoryRecord()
}

  function initMap() {
  // // 设置安全密钥
  // window._AMapSecurityConfig = {
  //   securityJsCode: '92e8196a027a174a0504f5e0de2e740d'
  // }

  // 创建地图实例时传入密钥
  map = new AMap.Map('container', {
    zoom: 15,
    center: [115.488995, 38.814947],
    features: ['bg', 'point', 'road'],
    mapStyle: 'amap://styles/normal', // 默认样式
    showIndoorMap: true, // 显示室内地图
    viewMode: '2D',
    pitch: 60,
    rotation: 0,
    expandZoomRange: true,
    zooms: [3, 20],

  })

  // 加载路线规划插件
  AMap.plugin('AMap.Driving', () => {
    driving.value = new AMap.Driving({
      map: map,
      policy: AMap.DrivingPolicy.LEAST_TIME, // 最快路线
      hideMarkers: true ,// 隐藏自带标记
      showTraffic: true // 可选：显示实时路况
    })
  })

  // 点击地图设置标记
  map.on('click', (e) => {
    // 设置坐标到添加表单
    newStation.value.positionStr = `${e.lnglat.lng.toFixed(6)}, ${e.lnglat.lat.toFixed(6)}`
    newStation.value.position = e.lnglat

    if (!marker1.value) {
      setMarker1(e.lnglat)
    } else if (!marker2.value) {
      setMarker2(e.lnglat)
    } else {
      // 已有两个标记，清除后重新开始
      clearMarkers()
      setMarker1(e.lnglat)
    }
  })

  // 初始化快递站标记
  initStationMarkers()

  loading.value = false
}

// 初始化快递站标记
function initStationMarkers() {
  // 清除现有标记
  clearStationMarkers()

  // 添加新标记
  deliveryStations.value.forEach(station => {
    // const marker = new AMap.Marker({
    //   // position: [station.position.lng, station.position.lat],
    //   // title: station.name,
    //   // content: `<div class="station-marker">${station.name}</div>`,
    //   // offset: new AMap.Pixel(-15, -15)
    addStationMarker(station)
  })
}
// 添加单个快递站标记
function addStationMarker(station) {
  // 添加 null 检查
  if (!map) return;
  const marker = new AMap.Marker({
    position: [station.position.lng, station.position.lat],
    title: station.name,
    content: `<div class="station-marker">${station.name}</div>`,
    offset: new AMap.Pixel(-15, -15)
  })
  // 点击标记事件
  marker.on('click', () => {
    if(map) {
      map.setCenter([station.position.lng, station.position.lat])
      map.setZoom(15)
    }
    })

  map.add(marker)
  stationMarkers.value.push({
    id: station.id,
    marker: marker
  })



}


// 删除快递站
function removeStation(index) {
  // 删除地图标记
  const markerItem = stationMarkers.value[index]

  // 删除地图标记
  if (markerItem && markerItem.marker) {
    map.remove(markerItem.marker);
  }

  stationMarkers.value.splice(index, 1)

  // 删除数据
  deliveryStations.value.splice(index, 1)
  ElMessage.success('快递站已删除')
}












function setMarker1(lnglat) {
  marker1.value = lnglat
  const marker = new AMap.Marker({
    position: lnglat,
    title: '标记1',
    label: { content: '起点' },
    offset: new AMap.Pixel(10, -20)
  })
  marker.setLabel({ content: '起点', offset: new AMap.Pixel(10, -25) })
  map.add(marker)

  // 存储标记实例和位置信息
  marker1.value = {
    lng: lnglat.lng,
    lat: lnglat.lat,
    marker: marker // 存储标记实例
  }
}

function setMarker2(lnglat) {
  marker2.value = lnglat
  const marker = new AMap.Marker({
    position: lnglat,
    title: '标记2',
    label: { content: '终点' },
    offset: new AMap.Pixel(10, -20),
    style: {
      color: '#fc0000',      // 文字颜色
      background: '#ff0000', // 背景色（紫色）
      border: 'none',     // 去掉边框
      padding: '2px 5px', // 内边距
      borderRadius: '3px' // 圆角
    }
  })
  map.add(marker)

  // 存储标记实例和位置信息
  marker2.value = {
    lng: lnglat.lng,
    lat: lnglat.lat,
    marker: marker // 存储标记实例
  }

  calculateDistance()

  // 新增路线规划调用
  planRoute() // 关键添加点
}

function calculateDistance() {
  if (marker1.value && marker2.value) {
    // 使用 AMap.GeometryUtil.distance 计算两点之间距离（单位：米）
    distance.value = AMap.GeometryUtil.distance(
        [marker1.value.lng, marker1.value.lat],
        [marker2.value.lng, marker2.value.lat]
    )
  }
}

function clearMarkers() {
  // 清除路线
  if (driving.value) {
    driving.value.clear()
  }
  // 只清除起点和终点标记
  if (marker1.value) {
    map.remove(marker1.value.marker) // 通过存储的标记实例移除
    marker1.value = null
  }

  if (marker2.value) {
    map.remove(marker2.value.marker) // 通过存储的标记实例移除
    marker2.value = null
  }

  routeInfo.value = null
  distance.value = 0
}

// 获取当前位置
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
      (position) => {
        const lat = position.coords.latitude
        const lng = position.coords.longitude
        map.setCenter([lng, lat])

        // 添加标记
        const marker = new AMap.Marker({
          position: new AMap.LngLat(lng, lat)
        })
        map.add(marker)

        loading.value = false
      },
      (error) => {
        console.error('定位失败:', error)
        loading.value = false
      }
  )
} else {
  loading.value = false

}








// 新增逆地理编码函数
const geocodePosition = async (lng, lat) => {
  return new Promise((resolve) => {
    AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new AMap.Geocoder()
      geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          resolve(result.regeocode.formattedAddress)
        } else {
          resolve(`${lng.toFixed(6)}, ${lat.toFixed(6)}`)
        }
      })
    })
  })
}

// const saveHistoryRecord = async () => {
//   // 检查必要数据是否存在
//   if (!routeInfo.value || !marker2.value) return
//
//   try {
//     // 获取起点地址
//     const startLng = currentPositionMarker.value?.getPosition().lng || marker1.value.lng
//     const startLat = currentPositionMarker.value?.getPosition().lat || marker1.value.lat
//     const startAddress = await geocodePosition(startLng, startLat)
//
//
//     // 获取终点地址
//     const endAddress = await geocodePosition(marker2.value.lng, marker2.value.lat)
//
//     // 创建记录对象
//     const record = {
//       id: Date.now(),
//       startTime: Date.now(),
//       startLng: startLng,
//       startLat: startLat,
//       startAddress: startAddress,
//       endLng: marker2.value.lng,
//       endLat: marker2.value.lat,
//       endAddress: endAddress,
//       distance: routeInfo.value.distance,
//       duration: routeInfo.value.time,
//
//       instruction: routeInfo.value.instruction,
//       nextInstruction: routeInfo.value.nextInstruction
//     }
//
//     // 保存到本地存储
//     const history = JSON.parse(localStorage.getItem('navigationHistory') || '[]')
//     history.unshift(record)
//     localStorage.setItem('navigationHistory', JSON.stringify(history))
//
//     ElMessage.success('导航记录已保存')
//   } catch (error) {
//     console.error('保存历史记录失败:', error)
//     ElMessage.error('保存历史记录失败')
//   }
// }







// 新增导航相关函数
function startNavigation() {
  if (!marker2.value) {
    ElMessage.warning('请先设置目的地')
    return
  }

  navigating.value = true
  planRoute() // 初始路线规划

  // 启动导航更新定时器
  navInterval = setInterval(() => {
    if (navigating.value) {
      updateNavigation()
    }
  }, 5000) // 每5秒更新一次导航
}

// 更新导航状态
function updateNavigation() {
  if (!driving.value || !routeInfo.value) return

  // 获取当前位置
  if (currentPositionMarker.value) {
    const currentPos = currentPositionMarker.value.getPosition()

    // 计算到终点的距离
    const distanceToEnd = AMap.GeometryUtil.distance(
        [currentPos.lng, currentPos.lat],
        [marker2.value.lng, marker2.value.lat]
    )

    // 如果接近终点，结束导航
    if (distanceToEnd < 50) { // 50米内视为到达
      stopNavigation()
      ElMessage.success('已到达目的地')
      return
    }

    // 重新规划路线（使用当前位置作为起点）
    planRoute()
  }
}

// 停止导航函数



// 修改路线规划函数以支持导航更新
function planRoute() {
  if (!driving.value || !marker2.value) return

  // 清除旧路线
  driving.value.clear()

  // 使用实时位置作为起点（如果存在）
  const startPosition = currentPositionMarker.value ?
      currentPositionMarker.value.getPosition() :
      new AMap.LngLat(marker1.value.lng, marker1.value.lat)
  const end = new AMap.LngLat(marker2.value.lng, marker2.value.lat)

  driving.value.search(startPosition, end, (status, result) => {
    if (status === 'complete') {
      const route = result.routes[0]
      const steps = route.steps

      // 提取路径点
      const pathPoints = steps.flatMap(step => step.path)

      // 提取导航指令
      let currentInstruction = '开始导航'
      let nextInstruction = '请沿当前道路直行'

      if (steps.length > 0) {
        currentInstruction = steps[0]?.instruction || '开始导航'
        nextInstruction = steps.length > 1 ?
            steps[1]?.instruction : '即将到达目的地'
      }

      routeInfo.value = {
        distance: route.distance,
        time: Math.round(route.time / 60), // 转换为分钟
        instruction: currentInstruction,
        nextInstruction: nextInstruction,
        pathPoints: pathPoints // 确保保存路径点
      }

      // 自动调整地图视野
      map.setFitView()
    } else {
      console.error('路线规划详细错误:', status, result)
      ElMessage.error('路线规划失败，请稍后重试')
    }
  })
}

// 修改保存函数保存路径点
const saveHistoryRecord = async () => {
  // 检查必要数据是否存在
  if (!routeInfo.value || !marker2.value) return

  try {
    // 获取起点地址
    const startLng = currentPositionMarker.value?.getPosition().lng || marker1.value.lng
    const startLat = currentPositionMarker.value?.getPosition().lat || marker1.value.lat
    const startAddress = await geocodePosition(startLng, startLat)

    // 获取终点地址
    const endAddress = await geocodePosition(marker2.value.lng, marker2.value.lat)

    // 创建记录对象
    const record = {
      id: Date.now(),
      startTime: Date.now(),
      startLng: startLng,
      startLat: startLat,
      startAddress: startAddress,
      endLng: marker2.value.lng,
      endLat: marker2.value.lat,
      endAddress: endAddress,
      distance: routeInfo.value.distance,
      duration: routeInfo.value.time,
      instruction: routeInfo.value.instruction,
      nextInstruction: routeInfo.value.nextInstruction,
      pathPoints: routeInfo.value.pathPoints // 保存实际路径点
    }

    // 保存到本地存储
    const history = JSON.parse(localStorage.getItem('navigationHistory') || '[]')
    history.unshift(record)
    localStorage.setItem('navigationHistory', JSON.stringify(history))

    ElMessage.success('导航记录已保存')
  } catch (error) {
    console.error('保存历史记录失败:', error)
    ElMessage.error('保存历史记录失败')
  }
}










</script>

<style scoped>
.map-layout {
  display: flex;
  height: calc(100vh - 60px);
}

.map-container {
  position: relative;
  flex: 1;
  width:100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.data-panel {
  width: 400px;
  padding: 15px;
  background: #fff;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.station-list {
  flex: 1;
  margin-bottom: 15px;
}

.stats {
  margin-top: auto;
}

/* 原有样式保持不变 */
.clear-btn {
  margin-top: 8px;
  display: block;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 3;
}

.amap {
  width: 100%;
  height: 100%;
}

.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 100;
  font-size: 1rem;
  color: #333;
}

.map-info {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 16px;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.stat-item {
  padding: 8px 0;
  font-size: 14px;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 新增实时定位标记样式 */
.current-position-marker {
  font-size: 24px;
  text-shadow: 0 0 3px white;
}
/* 快递站标记样式 */
.station-marker {
  background: #ff0000;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}



.nav-instructions {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(255, 255, 255, 0.9);
padding: 10px 16px;
border-radius: 6px;
z-index: 2;
max-width: 80%;
text-align: center;
}

/* 修改导航控制按钮的样式 */
.navigation-controls {
  position: absolute;
  top: 120px;
  right: 26px;
  z-index: 1000; /* 提高层级确保显示在最前面 */
  display: flex;
  gap: 8px;
  background: rgba(255, 255, 255, 0.8); /* 添加背景避免地图内容干扰 */
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}




</style>